const jwt = require('jsonwebtoken');
const { PUBLIC_KEY } = require('../app/config');
const { error_fun } = require('../app/constants/error-types');
const { API_message_500, API_message_401 } = require('../app/constants/messageAPI');
const md5password = require('../app/utils/password-handle');
const userService = require('../service/user.service');


//验证授权
const verifyAuth = async (ctx, next) => {

    const authorization = ctx.headers.authorization;

    if (!authorization) {
        ctx.body = API_message_401();
        return error_fun(ctx, "获取token错误")
    }
    const token = authorization.replace('Bearer ', '');
    
    //验证token
    try {
        const result = jwt.verify(token, PUBLIC_KEY, {
            algorithms: ['RS256']
        });
        ctx.user = result;
        await next();
    } catch(e) {
        console.log(e, "获取token错误")
    }
}

//登录授权
const verifyLogin = async (ctx, next) => {
    // 获取手机号和密码
    const { username, password } = ctx.request.body;

    //越界判断
    if (!username || !password) {
        ctx.body = API_message_500('用户名或密码不能为空');
        return error_fun(ctx, '没有接收到用户名或密码');
    }

    //判断用户是否存在
    const result = await userService.getUserByName(username);
    const user = result[0];
    if (!user) {
        ctx.body = API_message_500("用户不存在")
        return error_fun(ctx, '用户不存在')
    }

    //判断密码是否正确
    if (md5password(password) !== user.password) {
        ctx.body = API_message_500('密码错误');
        return error_fun(ctx, '密码错误')
    }

    //存储数据库获取的用户信息
    ctx.user = user;

    await next();
}

module.exports = { verifyAuth, verifyLogin }